package wsz.rpc.consumer.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * @author wsz
 * @date 2021/11/30 18:18
 **/
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext context;
    private String requestMsg;
    private String responseMsg;

    /**
     * 通道连接就绪
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    /**
     * 通道读就绪
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        try {
            responseMsg = msg;
            // 唤醒等待的线程
            notify();
        } catch (Exception ex) {
            ex.printStackTrace();
            // 唤醒等待的线程
            notify();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = context.channel();
        System.out.println("RpcClientHandler channelInactive---"+channel.isActive() + " ---" + channel.isOpen());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    @Override
    public synchronized Object call() throws Exception {
        try {
            context.writeAndFlush(requestMsg);
            wait();
            return responseMsg;
        } catch (Exception ex) {
            ex.printStackTrace();
            // 唤醒等待的线程
            notify();
            JSONObject object = new JSONObject();
            object.put("通道异常", ex.getMessage());
            return object;
        }
    }


    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

}
